<?php

namespace App\Exceptions;

use App\Utils\ElasticLog;
use App\Utils\Output;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {

        });
        $this->renderable(function (Throwable $e, $request) {
            if ($request->expectsJson() || $request->ajax() || Str::startsWith($request->path(), 'api')) {
                if ($e instanceof ValidationException) {
                    $result = Output::fail(
                        $e->validator->errors()->first(),
                        $e->getCode() ? intval($e->getCode()) : $e->getLine(),
                        $e->validator->errors()->toArray());
                } elseif ($e instanceof SysException) {
                    ElasticLog::error($request, $e);
                    Log::info($e->getMessage() . "\r\n" . $e->getTraceAsString());
                    $result = Output::fail($e->getMessage(), -1);
                } else {
                    ElasticLog::error($request, $e);
                    Log::info($e->getMessage() . "\r\n" . $e->getTraceAsString());
                    $result = Output::fail('系统异常', -1);
                }
                return response()->json($result);
            } else {
                ElasticLog::error($request, $e);
                return $this->prepareResponse($request, $e);
            }
        });

    }
}
